<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace App\Model\LazyCommon;

use App\Base\BaseModel;
use Doctrine\Bundle\DoctrineBundle\Registry;
use App\Setting\LazyCommon\UserLoginLogSetting;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;

class UserLoginLogModel extends BaseModel {


    /*
     * 列表基本设置【通用模块必须】
     */
    public function listSettingDefault()
    {
        $settings = new UserLoginLogSetting($this->getDoctrine());
        return $settings->listConfig();
    }

    public function getLastLoginInfo($account)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("User_Login_Log")->where("userAccount = :account")->setParameter("account",$account);
        $qb->orderBy("id","desc");
        $log = $qb->execute()->fetch();
        return $log;
    }

    public function createLoginLogInfo($request)
    {
        if (!$from = $request->request->get("from")) {
            $from = "";
        }

        switch ($from) {
            case "app":
                $username = $request->request->get("phone");
                $password = $request->request->get("password");
                $password = md5($password);
                break;
            case "web":
                $username = $request->request->get("_username");
                $password = $request->request->get("_password");
                $password = md5(md5($password));
                break;
            case "admin":
                $username = $request->request->get("_username");
                $password = $request->request->get("_password");
                $password = md5(md5($password));
                break;
            case "wechat":
                $username = $request->request->get("_username");
                $password = $request->request->get("_password");
                $password = md5(md5($password));
                break;
            default:
                $username = $request->request->get("username");
                $password = $request->request->get("password");
                $password = md5(md5($password));
        }


        $loginInfo = array(
            "userAccount"    => $username,
            "loginTime"      => time(),
            "loginIp"        => $_SERVER["REMOTE_ADDR"],
            "loginRequest"   => json_encode($_REQUEST),
            "userAgent"      => $_SERVER["HTTP_USER_AGENT"],
        );
        return $loginInfo;
    }

    public function addLoginLog($loginInfo)
    {
        $qb = $this->getQueryBuilder();
        $qb->insert("User_Login_Log");
        foreach ($loginInfo as $key => $val) {
            $qb->setValue("$key",":$key")->setParameter("$key",$val);
        }
        $qb->execute();
    }

}